/**
 * 前台教师PC端
 *        其他审批子模块JS代码
 */
function JsonOBJ() {
    this.id = null;
    this.majorname = null;
    this.classname = null;
    this.studentname = null;
    this.startTime = null;
    this.endTime = null;
    this.teachername = null;
    this.requestReason = null;
    this.rejectReason = null;
    this.authStatus = null;
    this.requestTime = null;
}

var pageNo = 1;     //当前页
var pageSize = 3;   //每页记录数
var pageCount = 1;
var tabCurrent = 0; //当前标签，待审批，代发，历史记录
var islogin = 1;
var isSubmit = 0;
var dataJson;  //查询参数
var type = 0;//查询类型：0 1 2 3 4
var para = new Array(4);//查询条件
var titleList = ["全部学院","全部专业","全部班级","全部年级"];
$(function () {
    /*--------------------------------------------------------------------*/
    $(".exit-btn").click(function () {
        $.ajax({
            url: "/door/front/teacher/exit?" + new Date().getTime(),
            async: false,
            success: function () {
                window.location.href = "/door/front_end/pc/teacher/login_pc_teacher.html";
            }
        });
    });
//  setTable(type, para);
    setOrg();
    toggleChecked();
    if ($("title").text() == "代理审批申请") {
        $("#sureBtn").click(function () {
            approveList(0);
        });
        $("#notSureBtn").click(function () {
            var i = 0;
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1)
                    i++;
            });
            if (i == 0) {
                layer.msg("至少勾选一条数据", {time: 1000});
            } else {
                $("#notSureModal").modal('show');
            }
        });
        $("#rejectBtn").click(function () {
            approveList(1);
            return false;
        });
        queryData();
    }
    
    if ($("title").text() == "家长审批") {
        $("#sureBtn").click(function () {
            approveList(0);
        });
        $("#notSureBtn").click(function () {
            var i = 0;
            $("img[id]").each(function () {
                if ($(this).attr("check_type") == 1)
                    i++;
            });
            if (i == 0) {
                layer.msg("至少勾选一条数据", {time: 1000});
            } else {
                $("#notSureModal").modal('show');
            }
        });
        $("#rejectBtn").click(function () {
            approveList(1);
            return false;
        });
        queryData();
    }

    
    init();
});

function init() {
    $.ajax({
        url: "/door/front/teacher/getCurTea?" + new Date().getTime(),
        async: false,
        success: function (str) {
            if (check(str)) {
                $("#teacher_name").text(str.teachername);
                $("#teacher_class").text(str.name);
            }
        }
    });
}

/**
 * 检查用户是否登录
 *    如果未登录，返回教师端登录页面
 * @param str
 * @returns {Boolean}
 */
function check(str) {
    if (str != null && str != "" || str == 0) {
        if (str.errorcode != undefined) {
            if (str.errorcode == 1) {
                if (islogin == 1) {
                    layer.msg(str.errormessage, {time: 1000});
                    window.location.href = "/door/front_end/pc/teacher/login_pc_teacher.html";
                    islogin = 0;
                }
            }
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}



//设置层次查询级联效果
var setOrg = function () {
    var url = "/door/StudentBack/getOrg?time=" + new Date().getTime();
    
    $.getJSON(url, function (strJSON) {
        //绑定学院按钮
        $("#ins button").click(function () {
            $("#ins ul li").remove();
            $("#ins ul").append("<li><a href='#'>全部学院</a></li>");
            $("#ins ul li:last").click(function () {
                $("#ins button").html($(this).text()+" <span class='caret'></span>");
                $("#major button").html("全部专业 <span class='caret'></span>");
                $("#class button").html("全部班级 <span class='caret'></span>");
                $("#search2").click();
                type = 1;
                
                para[0] = "";
                para[1] = "";
                para[2] = "";
                queryData();
            });
            for (var i = 0; i < strJSON.length; i++) {
                $("#ins ul").append("<li><a href='#'>" + strJSON[i].institutename + "</a></li>");
                $("#ins ul li:last").click(function () {
                    $("#ins button").text($(this).text());
                    $("#major button").html("全部专业 <span class='caret'></span>");
                    $("#class button").html("全部班级 <span class='caret'></span>");
                    $("#search2").click();
                    type = 1;
                    para[0] = $(this).text();
                    
                    para[1] = "";
                    para[2] = "";
                    queryData();
                })
            }
            //调用函数获取数据
           
        });
      
        //绑定专业按钮
        $("#major button").click(function () {
            $("#major ul li").remove();
            $("#major ul").append("<li><a href='#'>全部专业</a></li>");
            $("#major ul li:last").click(function () {
                $("#major button").html($(this).text()+" <span class='caret'></span>");
                $("#class button").html("全部班级 <span class='caret'></span>");
                $("#search2").click();
                type = 2;
                
                para[1] = "";
                para[2] = "";
                queryData();
            });
            for (var i = 0; i < strJSON.length; i++) {
                if (strJSON[i].institutename == $("#ins button").text()) {
                    for (var j = 0; j < strJSON[i].majorInfos.length; j++) {
                        $("#major ul").append("<li><a href='#'>" + strJSON[i].majorInfos[j].majorname + "</a></li>");
                        $("#major ul li:last").click(function () {
                            $("#major button").text($(this).text());
                            $("#class button").html("全部班级 <span class='caret'></span>");
                            $("#search2").click();
                            type = 2;
                            para[1] = $(this).text();
                            para[2] = "";
                            queryData();
                        })
                    }
                }
            }
        });
    
        //绑定班级按钮
        $("#class button").click(function () {
            $("#class ul li").remove();
            $("#class ul").append("<li><a href='#'>全部班级</a></li>");
            $("#class ul li:last").click(function () {
                $("#class button").html($(this).text()+" <span class='caret'></span>");
                $("#search2").click();
                type = 4;
                para[2] = "";
                queryData();
            });
            for (var i = 0; i < strJSON.length; i++) {
                if (strJSON[i].institutename == $("#ins button").text()) {
                    for (var j = 0; j < strJSON[i].majorInfos.length; j++) {
                        if (strJSON[i].majorInfos[j].majorname == $("#major button").text()) {
                            for (var k = 0; k < strJSON[i].majorInfos[j].classInfos.length; k++) {
                                $("#class ul").append("<li><a href='#'>" + strJSON[i].majorInfos[j].classInfos[k].classname + "</a></li>");
                                $("#class ul li:last").click(function () {
                                    $("#class button").text($(this).text());
                                    $("#search2").click();
                                    type = 4;
                                    para[2] = $(this).text();
                                    queryData();
                                    
                                });
                            }
                        }
                    }
                }
            }
        });
        // 绑定年级按钮
        $("#grade ul li").each(function (i) {
            if(i==0){
                $(this).click(function () {
                    $("#grade button").html($(this).text()+" <span class='caret'></span>");
                    $("#search2").click();
                    type = 3;
                    para[3] = "";
                    queryData();
                });
            }else{
                $(this).click(function () {
                    $("#grade button").text($(this).text());
                    $("#search2").click();
                    type = 3;
                    para[3] = $(this).text();
                    queryData();
                    
                });
            }
        });
    });
};


function setDataOfList(records) {
    $(".right-detail .apply-item").remove();
    var str = '';

    for (var i = 0; i < records.length; i++) {
        var status_str =  "审批中";
        var status_class = "state-ing";
       
        str += '<div class="apply-item text-center"><div><div class="checkBox fl">' +
        '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
        records[i].id + '></div><p>' +
        records[i].classname + '</p><p>' +
        records[i].studentname + '</p></div><div><label>请假时长：</label><p>' +
        DateUtils.format(new Date(records[i].startTime), "yyyy-MM-dd HH:mm:ss") + '</p><p>至</p><p>' +
        DateUtils.format(new Date(records[i].endTime), "yyyy-MM-dd HH:mm:ss") + '</p><p class="' +
        status_class + '">' +
        status_str + '</p></div><div><label>请假原因：</label><div class="reason">' +
        records[i].requestReason + '</div><a href="#" onclick="hisOnclick('+records[i].id+')"><p class="to-detail">查看详情>> </p></a></div></div>';
       
    }
    // $("#pageCount").text(pager.pageCount);
    $(".pagination-table").before(str);
}
function hisOnclick(id){
	sessionStorage.setItem("id", id);
	window.location.href="/door/front_end/pc/teacher/apply.detailsPC_teacher.html";//跳转到详情页...
	
	
	//在xxxx.html: 获取id;根据id获取详情(ajax)
}
function setDataOfStuList(students) {
    $("#students_ul").empty();
    var str = '';

    for (var i = 0; i < students.length; i++) {
        str += '<li class="col-sm-3 student-name"><ul class="student-area"><li class="fl checkBox margin-cancel">' +
            '<img src="../../../images/img_xuanzhe_01.png" alt="" class="check" check_type=0 id=' +
            students[i].code + '></li><li><h4 class="name-border">' +
            students[i].name + '<br/>' +
            students[i].code + '</h4></li></ul></li>'
    }

    $("#students_ul").html(str);
}

function queryData() {
    tabCurrent = $("#type").attr("value");
    var sdate = $("#date-start").val();
    var edate = $("#date-end").val();
    var stuName = $(".seek-box").val();

    if (typeof(sdate) == "undefined" || sdate == "") {
        sdate = "1970-01-01 00:00:00";
    }
    if (typeof(edate) == "undefined" || edate == "") {
        edate = "2160-01-01 00:00:00";
    }
    if (typeof(stuName) == "undefined") {
        stuName = "";
    }
    dataJson = {
        startDate: sdate,
        endDate: edate,
        stuName: stuName,
        pageNo: pageNo,
        pageSize: pageSize,
        type: type,
        para: para
    };
    getDataOfRecord();
}

//function queryDataOfStu() {
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/door/front/teacher/getCurTeaStus',
//        data: {
//            pageSize: 24,
//            pageNo: pageNo
//        },
//        cache: false,
//        dataType: 'json',
//        contentType: 'application/x-www-form-urlencoded',
//        beforeSend: function (xhr) {
//        },
//        success: function (data, textStatus, xhr) {
//            if (check(data)) {
//                if (data.itemCount == 0) {
//                    layer.msg("没有数据", {time: 1000});
//                }
//                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
//                setTableBTN();
//                setDataOfStuList(data.list);
//                toggleChecked();
//            }
//        },
//        error: function (xhr, textStatus, errorInfo) {
//        },
//        complete: function (xhr, textStatus) {
//        }
//    });
//}

function getDataOfRecord() {//带参分页查询函数
    $.ajax({
        async: true,
        type: 'POST',
        url: '/door/front/teacher/allApplys',
        traditional:true,
        data: {
        	pageNo: pageNo,
            pageSize: pageSize,
            type: type,
            para: para.toString()
        },
        //data: {type: type,para: para,pageNo:pageNo,pageSize: 24},
        //data: {type: type,data0: para[0],data1: para[1],data2: para[2],data3: para[3],pageNo:pageNo,pageSize: 3},
        cache: false,
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded',
        beforeSend: function (xhr) {
        },
        success: function (data, textStatus, xhr) {
            if (check(data)) {
                if (data.itemCount == 0) {
                    layer.msg("没有数据", {time: 1000});
                }
                pageCount = Math.floor((data.itemCount + pageSize - 1) / pageSize);
                setTableBTN();
                setDataOfList(data.list);
                toggleChecked2();
            }
        },
        error: function (xhr, textStatus, errorInfo) {
        },
        complete: function (xhr, textStatus) {
        }
    });
}

function setTableBTN() {
    var pagination_li = $(".pager li");
    var pagination_a = $(".pager a");

    if(pageNo==1){
        pagination_a.eq(6).html(pageNo + 4);
        pagination_a.eq(5).html(pageNo + 3);
        pagination_a.eq(4).html(pageNo + 2);
        pagination_a.eq(3).html(pageNo + 1);
        pagination_a.eq(2).html(pageNo);
        pagination_li.each(function (i) {
            $(this).removeClass("active");
            if (pageNo == parseInt($(this).text())) {
                $(this).addClass("active");
            }
        });
    }

    pagination_li.each(function (i) {
        if (i == 1) {//上一页按钮
            this.onclick = function () {
                if (pageNo > 1) {
                    pageNo--;

                    if (pageNo < parseInt(pagination_a.eq(2).html())) {
                        pagination_a.eq(6).html(pageNo + 4);
                        pagination_a.eq(5).html(pageNo + 3);
                        pagination_a.eq(4).html(pageNo + 2);
                        pagination_a.eq(3).html(pageNo + 1);
                        pagination_a.eq(2).html(pageNo);
                    }
                    pagination_li.each(function (i) {
                        $(this).removeClass("active");
                        if (pageNo == parseInt($(this).text())) {
                            $(this).addClass("active");
                        }
                    });
                    queryData();
                } else {
                    layer.msg("当前是第一页", {time: 1000});
                }
            };
        } else if (i == 7) {//下一页按钮
            this.onclick = function () {
                if (pageNo < pageCount) {
                    pageNo++;

                    if (pageNo > parseInt(pagination_a.eq(6).html())) {
                        pagination_a.eq(6).html(pageNo);
                        pagination_a.eq(5).html(pageNo - 1);
                        pagination_a.eq(4).html(pageNo - 2);
                        pagination_a.eq(3).html(pageNo - 3);
                        pagination_a.eq(2).html(pageNo - 4);
                    }
                    pagination_li.each(function (i) {
                        $(this).removeClass("active");
                        if (pageNo == parseInt($(this).text())) {
                            $(this).addClass("active");
                        }
                    });
                    queryData();
                } else {
                    layer.msg("当前是最后一页", {time: 1000});
                }
            };
        } else if (i == 0) {
            this.onclick = function () {
                pageNo = 1;

                if (pageNo < parseInt(pagination_a.eq(2).html())) {
                    pagination_a.eq(6).html(pageNo + 4);
                    pagination_a.eq(5).html(pageNo + 3);
                    pagination_a.eq(4).html(pageNo + 2);
                    pagination_a.eq(3).html(pageNo + 1);
                    pagination_a.eq(2).html(pageNo);
                }
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            };
        } else if (i == 8) {
            this.onclick = function () {
                pageNo = pageCount;

                if (pageNo > parseInt(pagination_a.eq(6).html())) {
                    pagination_a.eq(6).html(pageNo);
                    pagination_a.eq(5).html(pageNo - 1);
                    pagination_a.eq(4).html(pageNo - 2);
                    pagination_a.eq(3).html(pageNo - 3);
                    pagination_a.eq(2).html(pageNo - 4);
                }
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            };
        } else {//普通翻页按钮
            this.onclick = function () {
                var index = parseInt(this.innerText);
                if (index > pageCount) {
                    index = pageCount;
                    layer.msg("共" + pageCount + "页", {time: 1000});
                }
                pageNo = index;
                pagination_li.each(function (i) {
                    $(this).removeClass("active");
                    if (pageNo == parseInt($(this).text())) {
                        $(this).addClass("active");
                    }
                });
                queryData();
            }
        }
    });
}


function toggleChecked2(){
	 $(".checkBox img").each(function () {
	        $(this).click(function () {
	            if ($(this).attr("check_type") == 0) {
	                $(this).attr("check_type", 1);
	                $(this).attr("src", "../../../images/img_xuanzhe_02.png")
	            } else {
	                $(this).attr("check_type", 0);
	                $(this).attr("src", "../../../images/img_xuanzhe_01.png")
	            }
	        })
	    });
}

function toggleChecked() {
   
    $(".allCheck img").click(function () {
        if ($(this).attr("check_type") == 0) {
            $(this).attr("check_type", 1);
            $(this).attr("src", "../../../images/img_xuanzhe_02.png");
            $(".checkBox img").each(function () {
                $(this).attr("check_type", 1);
                $(this).attr("src", "../../../images/img_xuanzhe_02.png")
            });
        } else {
            $(this).attr("check_type", 0);
            $(this).attr("src", "../../../images/img_xuanzhe_01.png");
            $(".checkBox img").each(function () {
                $(this).attr("check_type", 0);
                $(this).attr("src", "../../../images/img_xuanzhe_01.png");
            });
        }
    });
}

//function replaceList() {
//    if (checkInput() == 0) {
//        var checkIds = new Array();
//        $("img[id]").each(function () {
//            if ($(this).attr("check_type") == 1) {
//                var js = new JsonOBJ();
//                js.studentname = $(this).attr("id");
//                js.requestReason = $("#causeBack").val();
//                js.startTime = new Date($("#date-start").val());
//                js.endTime = new Date($("#date-end").val());
//                checkIds.push(js);
//            }
//        });
//        $("#replaceModal").modal('hide');
//        $.ajax({
//            url: "/door/front/teacher/replace?" + new Date().getTime(),
//            type: "post",
//            data: JSON.stringify(checkIds),
//            dataType: "json",
//            contentType: "application/json; charset=utf-8",
//            async: false,
//            success: function (str) {
//                if (check(str)) {
//                    if (checkIds.length != parseInt(str)) {
//                        layer.msg("失败" + (checkIds.length - parseInt(str)) + "条", {time: 1500});
//                    } else {
//                        layer.msg("代发成功", {time: 1500});
//                    }
//                }
//            }
//        });
//    }
//}

function approveList(type) {
    var checkIds = new Array();
    $("img[id]").each(function () {
        if ($(this).attr("check_type") == 1) {
            var js = new JsonOBJ();
            js.id = $(this).attr("id");
            if (type == 0) {
                js.authStatus = 1;
                js.rejectReason = "";
            } else {
                js.authStatus = 2;
                js.rejectReason = $("#caused").val();
            }
            checkIds.push(js);
        }
    });
    if ($("#caused").val() == "" && type == 1) {
        layer.msg("拒绝理由不能为空", {time: 1000});
        return;
    }
    if (checkIds.length == 0) {
        layer.msg("至少勾选一条数据", {time: 1000});
    } else {
        $.ajax({
            url: "/door/front/teacher/approve?" + new Date().getTime(),
            type: "post",
            data: JSON.stringify(checkIds),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            async: false,
            success: function (str) {
                if (check(str)) {
                    $("#notSureModal").modal('hide');
                    if (type == 0) {
                        if (str == checkIds.length) {
                            $('#myModalLabel').text('批准成功');
                            $("#modal-body").text('已批准成功！');
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        } else {
                            $('#myModalLabel').text('批准失败');
                            $("#modal-body").text("失败" + (checkIds.length - parseInt(str)) + "条！");
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        }
                    } else {
                        if (str == checkIds.length) {
                            $('#myModalLabel').text('不批准');
                            $("#modal-body").text('提交成功！');
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        } else {
                            $('#myModalLabel').text('不批准');
                            $("#modal-body").text("失败" + (checkIds.length - parseInt(str)) + "条！");
                            $("#sureModal").modal('show');
                            pageNo = 1;
                            queryData();
                        }
                    }
                }
            }
        });
    }
}

//function checkInput() {
//    var st = $("#date-start").val();
//    var et = $("#date-end").val();
//    var reason = $("#causeBack").val();
//    if (st != "" && et != "") {
//
//        if (reason != "") {
//            var sTime = new Date(st);
//            var eTime = new Date(et);
//            var nTime = new Date();
//            if (sTime <= nTime) {
//                layer.msg("起始日期不能早于当前时间", {time: 1000});
//                return 3;
//            } else if (sTime >= eTime) {
//                layer.msg("结束日期不能早于起始日期", {time: 1000});
//                return 4;
//            } else {
//                return 0;
//            }
//        } else {
//            layer.msg("请假原因不能为空", {time: 1000});
//            return 2;
//        }
//    } else {
//
//        layer.msg("日期不能为空", {time: 1000});
//        return 1;
//    }
//}